package com.atguigu.web;

import com.atguigu.pojo.Cart;
import com.atguigu.pojo.User;
import com.atguigu.service.OrderService;
import com.atguigu.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 14587
 * @date 2020/10/24 21:41
 */
public class OrderServlet extends BaseServlet{
    private OrderService orderService=new OrderServiceImpl();
    /**
     * @author VegetDog
     * @Description 生成订单
     * @date 2020-10-24 21:43
     * @param req
 * @param resp
     * @return void
     */
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //首先要获取userId和cart对象
        Cart cart= (Cart) req.getSession().getAttribute("cart");
        User loginUser = (User) req.getSession().getAttribute("user");
        if (loginUser==null){
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
            return;
        }
        Integer id = loginUser.getId();
        // 调用orderService.createOrder方法创建订单
        String orderId = null;

        //由于我们在filter中过滤了信息，给所有的业务都加入了try catch，所以就不需要了

        /*try {
            orderId = orderService.createOrder(id, cart);
            //看是否有异常，没有就提交
            jdbcUtils.commitAndClose();
        } catch (Exception e) {
            jdbcUtils.rollbackAndClose();
            e.printStackTrace();
        }*/

        orderId = orderService.createOrder(id, cart);

        req.getSession().setAttribute("orderId",orderId);
        //请求转发到/pages/cart/checkout.jsp
        resp.sendRedirect(req.getContextPath()+"/pages/cart/checkout.jsp");
    }
}
